package com.ai.wx.quartz;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.core.util.Configure;
import com.ai.wx.entity.ProductOrder;
import com.ai.wx.http.FlowCloudHttpPostHelper;
import com.ai.wx.pojo.AccessToken;
import com.ai.wx.pojo.FlowCloudPostResult;
import com.ai.wx.service.ProductOrderService;
import com.ai.wx.service.SystemService;
import com.ai.wx.util.WeixinUtil;
import com.alibaba.fastjson.JSONObject;

@Service("quartz")
public class Quartz {
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProductOrderService productOrderService;

	public void updateAccessToken() {
		// 调用接口获取access_token
		AccessToken at = WeixinUtil.getAccessToken(Configure.getAppId(), Configure.getAppsecret());
		if (null != at) {
			String accessToken = at.getToken();
			systemService.updateAccessToken(accessToken);

			String jsapiTicket = WeixinUtil.getJsapiTicket(accessToken);
			if (null != jsapiTicket) {
				systemService.updateJsapiTicket(jsapiTicket);
			}
		}

	}

	public void processPaidOrder() {
		List<ProductOrder> todoOrderList = productOrderService.batchDoProductOrder();
		for (ProductOrder productOrder : todoOrderList) {
			try {

				String mobile = productOrder.getMobile();
				String productId = productOrder.getProductId();
				String postResult = FlowCloudHttpPostHelper.doPost(mobile, productId, getTimeStamp());
				if (StringUtils.isNotEmpty(postResult)) {
					postResult = StringUtils.trim(postResult);
					int beginIndex = postResult.indexOf("{");

					int endIndex = postResult.lastIndexOf("}")+1;
					String json = postResult.substring(beginIndex, endIndex);
					FlowCloudPostResult rtnObj = JSONObject.parseObject(json, FlowCloudPostResult.class);
					String orderMsg= postResult;
					if(orderMsg.length()>1000){
						orderMsg = orderMsg.substring(0,900);
					}
					productOrder.setOrderMsg(orderMsg);
					if(StringUtils.equals("0", rtnObj.getResult())){//充值成功
						 
						productOrderService.productOrderSuccess(productOrder);
					}else{
						 
						productOrderService.productOrderFail(productOrder);
					}
				}
			} catch (Exception e) {
				String orderMsg= e.getMessage();
				if(orderMsg.length()>1000){
					orderMsg = orderMsg.substring(0,900);
				}
				productOrder.setOrderMsg(orderMsg);
				productOrderService.productOrderFail(productOrder);
				e.printStackTrace();
			}
		}
	}

	public static String getTimeStamp() {

		Calendar cal = Calendar.getInstance();
		java.util.Date date = cal.getTime();

		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");

		return sdFormat.format(date);
	}
}
